<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <h1 class="login-title">超市商品溯源管理系统</h1>
        <p class="login-subtitle">安全可靠的商品追踪解决方案</p>
      </div>
      
      <el-form 
        ref="loginFormRef" 
        :model="loginForm" 
        :rules="loginRules" 
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            size="large"
            prefix-icon="User"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            prefix-icon="Lock"
            show-password
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <el-form-item>
          <div class="login-options">
            <el-checkbox v-model="loginForm.remember">记住密码</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            size="large" 
            class="login-button"
            :loading="loading"
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
        
        <el-form-item>
          <div class="register-link">
            还没有账号？
            <el-link type="primary" :underline="false" @click="goToRegister">
              立即注册
            </el-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
    
    <div class="login-footer">
      <p>&copy; 2024 超市商品溯源管理系统. All rights reserved.</p>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { setToken, setUserInfo } from '@/utils/auth'

export default defineComponent({
  name: 'Login',
  setup() {
    const router = useRouter()
    const loginFormRef = ref(null)
    const loading = ref(false)
    
    // 表单数据
    const loginForm = reactive({
      username: '',
      password: '',
      remember: false
    })
    
    // 表单验证规则
    const loginRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ]
    }
    
    // 登录处理
    const handleLogin = async () => {
      if (!loginFormRef.value) return
      
      try {
        const valid = await loginFormRef.value.validate()
        if (!valid) return
        
        loading.value = true
        
        // 模拟登录API调用
        await simulateLogin()
        
        ElMessage.success('登录成功')
        
        // 跳转到首页 - 使用replace避免浏览器后退
        console.log('准备跳转到 /dashboard')
        await router.replace('/dashboard')
        console.log('跳转完成')
        
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error('登录失败，请检查用户名和密码')
      } finally {
        loading.value = false
      }
    }
    
    // 模拟登录
    const simulateLogin = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          // 模拟验证
          if (loginForm.username === 'admin' && loginForm.password === '123456') {
            // 设置token和用户信息
            setToken('mock-token-123456')
            setUserInfo({
              id: 1,
              username: 'admin',
              email: 'admin@example.com',
              role: 'admin',
              permissions: ['admin', 'user']
            })
            
            // 设置本地存储
            localStorage.setItem('userRole', 'admin')
            localStorage.setItem('userPermissions', JSON.stringify(['admin', 'user']))
            
            resolve()
          } else {
            reject(new Error('用户名或密码错误'))
          }
        }, 800)
      })
    }
    
    // 跳转到注册页面
    const goToRegister = () => {
      router.push('/register')
    }
    
    return {
      loginFormRef,
      loginForm,
      loginRules,
      loading,
      handleLogin,
      goToRegister
    }
  }
})
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 20"><defs><radialGradient id="a" cx="50%" cy="50%"><stop offset="0%" stop-color="rgba(255,255,255,.1)"/><stop offset="100%" stop-color="rgba(255,255,255,0)"/></radialGradient></defs><circle fill="url(%23a)" cx="10" cy="10" r="10"/><circle fill="url(%23a)" cx="30" cy="10" r="10"/><circle fill="url(%23a)" cx="50" cy="10" r="10"/><circle fill="url(%23a)" cx="70" cy="10" r="10"/><circle fill="url(%23a)" cx="90" cy="10" r="10"/></svg>') repeat;
    opacity: 0.1;
  }
}

.login-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 40px;
  width: 100%;
  max-width: 400px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;
  
  @include respond-to(xs) {
    padding: 24px;
  }
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
  
  .login-title {
    font-size: 24px;
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 8px;
    
    @include respond-to(xs) {
      font-size: 20px;
    }
  }
  
  .login-subtitle {
    font-size: 14px;
    color: #6b7280;
    margin: 0;
  }
}

.login-form {
  .el-form-item {
    margin-bottom: 24px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .el-input {
    :deep(.el-input__wrapper) {
      border-radius: 8px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      border: 1px solid #e5e7eb;
      
      &:hover {
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
      }
      
      &.is-focus {
        box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
        border-color: var(--el-color-primary);
      }
    }
  }
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  
  .el-checkbox {
    :deep(.el-checkbox__label) {
      font-size: 14px;
      color: #6b7280;
    }
  }
  
  .el-link {
    font-size: 14px;
  }
}

.login-button {
  width: 100%;
  height: 44px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  
  &:hover {
    background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  }
  
  &:active {
    background: linear-gradient(135deg, #4f5bc6 0%, #5e377e 100%);
  }
}

.register-link {
  text-align: center;
  font-size: 14px;
  color: #6b7280;
  
  .el-link {
    font-size: 14px;
    margin-left: 4px;
  }
}

.login-footer {
  position: absolute;
  bottom: 20px;
  text-align: center;
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
  z-index: 1;
  
  @include respond-to(xs) {
    position: static;
    margin-top: 24px;
    color: rgba(255, 255, 255, 0.9);
  }
}

// 移动端优化
@include respond-to(xs) {
  .login-container {
    padding: 16px;
    min-height: 100vh;
    justify-content: flex-start;
    padding-top: 60px;
  }
  
  .login-card {
    max-width: none;
    border-radius: 12px;
  }
}
</style> 